<template>
    <div class="page-container">
        <el-row style="margin: 10px 0" justify="space-between">
            <el-row>
                <el-button size="small" type="primary" :icon="Plus" @click="openForm(null)">新建</el-button>
                <el-button size="small" type="warning" @click="resetParams">全部数据</el-button>
            </el-row>
            <el-row>
                <el-button type="default" size="small" @click="headerVisible = true">表头设置</el-button>
            </el-row>
        </el-row>

        <div class="table-box">
            <el-table size="small" :data="tableList" class="table-list" stripe border :cell-style="{textAlign: 'center'}" :header-cell-style="{textAlign: 'center'}">
                <el-table-column v-for="item in header" :key="item.label" :prop="item.label" :min-width="item.width" :class-name="item.label !== 'productName' ? '' : 'order-goods'" align="center">
                    <template #header>
                        <span v-if="item.label !== 'productName'">{{ item.name }}</span>
                        <el-row v-else class="order-row-item order-border-none">
                            <el-col :span="6">产品名称</el-col>
                            <el-col :span="6">详情规格</el-col>
                            <el-col :span="4">数量</el-col>
                            <el-col :span="4">单价(元)</el-col>
                            <el-col :span="4">小计(元)</el-col>
                        </el-row>
                        <!-- 可搜索表头 -->
                        <el-popover placement="bottom" :width="200" trigger="click" v-if="item.isFilter && item.filter == 'search'">
                            <template #reference>
                                <el-icon :size="15" :color="params[item.label] ? 'var(--el-color-warning)' : 'var(--el-color-primary)'" style="margin-left: 2px">
                                    <ele-Search/>
                                </el-icon>
                            </template>
                            <el-input :placeholder="`请输入${item.name}`" v-model.trim="params[item.label]" size="small" clearable @input="getTableList"/>
                        </el-popover>
                        <!-- 可筛选表头 -->
                        <el-popover placement="bottom" :width="120" trigger="click" v-if="item.isFilter && item.filter == 'filter'">
                            <template #reference>
                                <el-icon :size="15" :color="params[item.label == 'shortName' ? 'supplierInfoId' : item.label] ? 'var(--el-color-warning)' : 'var(--el-color-primary)'" style="margin-left: 2px">
                                    <ele-Filter/>
                                </el-icon>
                            </template>
                            <el-scrollbar max-height="600px">
                                <el-radio-group v-model="params[item.label == 'shortName' ? 'supplierInfoId' : item.label]" size="small" v-if="filterData[item.label == 'shortName' ? 'supplierInfoId' : item.label] && filterData[item.label == 'shortName' ? 'supplierInfoId' : item.label].length > 0">
                                    <el-radio
                                        v-for="radio in filterData[item.label == 'shortName' ? 'supplierInfoId' : item.label]"
                                        :key="radio.value"
                                        :label="radio.value"
                                        @click.prevent="radioChange(radio.value, item.label == 'shortName' ? 'supplierInfoId' : item.label)">
                                        {{ radio.name }}
                                    </el-radio>
                                </el-radio-group>
                                <el-empty style="padding: 0;font-size:12px;" v-else :image-size="50" description="无数据"/>
                            </el-scrollbar>
                        </el-popover>
                    </template>
                    <template #default="{row}">
                        <div v-if="item.label === 'title'" class="primary" @click="openDetail(row)">{{ row.title }}</div>
                        <!-- 产品名称 -->
                        <div v-else-if="item.label === 'productName'" style="flex:1;display:flex;flex-direction: column">
                            <div v-for="(product, index) in row.productItems" :key="product.id" style="flex: 1;height:100%">
                                <el-row class="order-row-item" style="height:100%">
                                    <el-col :span="6">{{ product.name }}</el-col>
                                    <el-col :span="6">{{ product.specification }}</el-col>
                                    <el-col :span="4">{{ product.num }}</el-col>
                                    <el-col :span="4">{{ product.price.toFixed(2) }}</el-col>
                                    <el-col :span="4">{{ product.total.toFixed(2) }}</el-col>
                                </el-row>
                                <el-divider style="margin: 0 -8px;width:calc(100% + 16px);border-color:var(--el-border-color-light)" v-if="index < row.productItems.length - 1"/>
                            </div>
                        </div>
                        <div v-else-if="item.label === 'approveState'">{{ row.approve == 0 ? '无需审批' : (row.approveState == 1 ? '已审批' : '待审批') }}</div>
                        <div v-else>{{ row[item.label] }}</div>
                    </template>

                </el-table-column>
                <el-table-column label="操作" fixed="right" width="130" align="center">
                    <template v-slot="{row}">
                        <el-button size="small" type="primary" link @click="removeQuotation(row)">删除</el-button>
                        <el-button size="small" type="primary" link @click="toPurchase(row)">生成采购单</el-button>
                    </template>
                </el-table-column>
                <el-table-column label="发送方式" width="90">
                    <template v-slot="{row}">
                        <el-button size="small" type="primary" link v-if="row.directSend == 1" @click="directSend(row)"><i class="fa fa-envelope-o"/>直发</el-button>
                        <el-button size="small" type="primary" link v-else @click="wechatSend(row)"><i class="fa fa-weixin"/>微信</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <div class="page-block">
            <el-pagination v-model:currentPage="params.current" v-model:page-size="params.size" :page-sizes="[10, 20, 30, 40]" :small="true" :disabled="false" :background="false" layout="total, sizes, prev, pager, next, jumper" :total="total" :hide-on-single-page="true" @size-change="sizeChange" @current-change="currentChange"/>
        </div>

        <!-- 表头设置对话框 -->
        <el-dialog title="表头设置" v-model="headerVisible" destroy-on-close width="40%" @close="headerVisible = false" @opened="dialogOpened" top="5vh">
            <el-table ref="tableHeaderRef" :data="allHeader" @selection-change="headerChange" stripe border :cell-style="{textAlign: 'center'}" row-key="label"
                      :header-cell-style="{textAlign: 'center', background: 'var(--el-color-primary-light-9)', color: 'var(--next-bg-menuBar-light-1)'}">
                <el-table-column type="selection" width="90"/>
                <el-table-column label="表头名称" prop="name"/>
            </el-table>
            <template #footer>
                <el-button size="small" @click="headerVisible = false">关闭</el-button>
                <el-button size="small" type="primary" @click="submitHeader">保存</el-button>
            </template>
        </el-dialog>

        <el-dialog :title="editData && editData.id ? '编辑报价单' : '添加报价单'" v-model="createVisible" destroy-on-close width="40%" @close="createVisible = false" top="5vh">
            <quotation-order code="QUOTATION_ORDER" v-model:edit-form="editData" @callback="createCallback"/>
        </el-dialog>
        <!-- 转采购单 -->
        <purchase-order v-model:code="purchaseVisible" v-model:edit-form="purchaseForm"/>
        <!-- 详情 -->
        <quotation-detail v-model:drawer="detailDrawer" v-model:quotation="detailData" @callback="getTableList"/>
    </div>
</template>

<script>
import {onMounted, reactive, toRefs, ref} from 'vue'
import {Plus, Search} from '@element-plus/icons-vue'
import QuotationOrder from '/@/views/matter/supplier/QuotationOrder.vue'
import PurchaseOrder from '/@/views/matter/supplier/PurchaseOrder.vue'
import QuotationDetail from '/@/views/procure/components/QuotationDetail.vue'
import {getQuotePage, deleteQuote, getHeaders, saveHeader, sendQuote} from '/@/api/supplier/quoteOrder'
import {ElMessage, ElMessageBox} from 'element-plus'
import {getSupplierSelector} from '/@/api/supplier'

export default {
    name: 'Quotation',
    components: {
        QuotationOrder,
        PurchaseOrder,
        QuotationDetail
    },
    setup() {
        const tableHeaderRef = ref()
        const state = reactive({
            params: {
                current: 1,
                size: 10,
                quoteNo: null,
                title: null,
                supplierInfoId: null,
                approveState: null
            },
            tableList: [],
            total: 0,
            header: [],
            allHeader: [
                {
                    name: '报价单号',
                    isFilter: true,
                    filter: 'search',
                    label: 'quoteNo',
                    width: '140',
                    sort: 0
                }, {
                    name: '报价主题',
                    isFilter: true,
                    filter: 'search',
                    label: 'title',
                    width: '120',
                    sort: 1
                }, {
                    name: '报价单位',
                    isFilter: true,
                    filter: 'filter',
                    label: 'shortName',
                    width: '100',
                    sort: 2
                }, {
                    name: '报价金额',
                    isFilter: false,
                    filter: '',
                    label: 'amount',
                    width: '90',
                    sort: 3
                }, {
                    name: '产品清单',
                    isFilter: false,
                    filter: '',
                    label: 'productName',
                    width: '600',
                    sort: 4
                }, {
                    name: '审批状态',
                    isFilter: true,
                    filter: 'filter',
                    label: 'approveState',
                    width: '90',
                    sort: 5
                }, {
                    name: '备注',
                    isFilter: false,
                    filter: '',
                    label: 'remark',
                    width: '100',
                    sort: 6
                }
            ],
            selectedHeader: [],
            headerVisible: false,
            filterData: {
                approveState: [{name: '无需审批', value: 0}, {name: '已审批', value: 1}, {name: '未审批', value: 2}],
                supplierInfoId: []
            },
            createVisible: false,    // QUOTATION_ORDER
            editData: null,
            purchaseForm: {},
            purchaseVisible: '',   // Purchase_Order
            detailDrawer: false,
            detailData: {}
        })

        const sizeChange = (size) => {
            state.params.size = size
            currentChange(1)
        }
        const currentChange = (current) => {
            state.params.current = current
            getTableList()
        }
        const getTableList = () => {
            getQuotePage(state.params).then(res => {
                state.total = res.data.total
                state.tableList = res.data.records
            }).catch(e => console.log(e))
        }
        // 直发
        const directSend = (quotation) => {
            ElMessageBox.confirm('确定把报价单 “' + quotation.title + '” 发送给对方？', '提示', {
                confirmButtonText: '发送',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                sendQuote(quotation).then(res => {
                    if (res.data) {
                        ElMessage.success('发送成功!')
                    }
                }).catch(e => console.log(e))
            }).catch(err => console.log(err))
        }
        // 微信转发
        const wechatSend = (quotation) => {
            navigator.clipboard.writeText(import.meta.env.VITE_SHARE_URL + '/quotationOrder/' + quotation.id).then(() => ElMessage.success('复制成功！'))
        }
        const openForm = (item) => {
            if (item && item.id) {
                state.editData = JSON.parse(JSON.stringify(item))
            } else {
                state.editData = null
            }
            state.createVisible = true
        }
        // 删除报价单
        const removeQuotation = (quotation) => {
            ElMessageBox.confirm('确定删除 “' + quotation.title + '” 报价单？', '提示', {
                confirmButtonText: '删除',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                deleteQuote(quotation).then(res => {
                    if (res.data) {
                        ElMessage.success('删除成功！')
                        getTableList()
                    }
                }).catch(e => console.log(e))
            }).catch(err => console.log(err))

        }
        // 生成采购单
        const toPurchase = (quotation) => {
            state.purchaseForm = {
                id: null,
                supplierInfoId: quotation.supplierInfoId,
                title: quotation.title,
                contractAmount: quotation.amount,
                stage: null,
                type: 1,
                source: quotation.source,
                handlerId: quotation.contactUserId,
                handlerPhone: quotation.contactPhone,
                amountTax: quotation.amountTax,
                paymentType: quotation.paymentType,
                invoice: 0,
                invoiceType: null,
                productAmountSum: quotation.productAmountSum,
                productItems: quotation.productItems,
                remark: quotation.remark
            }
            state.purchaseVisible = 'PURCHASE_ORDER'
        }
        // 打开详情
        const openDetail = (quotation) => {
            state.detailData = JSON.parse(JSON.stringify(quotation))
            state.detailDrawer = true
        }
        // 筛选
        const radioChange = (val, name) => {
            // 重复点击同个值取消选中
            state.params[name] = state.params[name] == val ? null : val
            getTableList()
        }
        // 重置参数
        const resetParams = () => {
            state.params = {
                current: 1,
                size: 10,
                quoteNo: null,
                title: null,
                supplierInfoId: null,
                approveState: null
            }
            getTableList()
        }
        // 表头对话框的回调
        const dialogOpened = () => {
            state.header.forEach(item => {
                state.selectedHeader.push(item)
                tableHeaderRef.value.toggleRowSelection(item, true)
            })
        }
        const headerChange = (list) => {
            if (state.selectedHeader.length > list.length) {
                state.selectedHeader = list
            } else {
                const item = list[list.length - 1]
                state.selectedHeader.splice(item.sort, 0, item)
            }
        }
        // 保存表头数据
        const submitHeader = () => {
            saveHeader(state.selectedHeader).then(res => {
                state.header = Object.assign([], state.selectedHeader)
                state.headerVisible = false
                ElMessage.success('保存成功！')
            }).catch(e => console.log(e))
        }
        // 创建框关闭回调
        const createCallback = () => {
            getTableList()
        }

        onMounted(() => {
            getHeaders().then(res => {
                if (res.data && res.data.length > 0) {
                    res.data.forEach(item => {
                        for (let i = 0; i < state.allHeader.length; i++) {
                            let headerItem = state.allHeader[i]
                            if (item.label == headerItem.label) {
                                state.header.push(headerItem)
                            }
                        }
                    })
                } else {
                    state.header = state.allHeader
                }
            }).catch(e => console.log(e))
            // 获取供应商列表
            state.filterData.supplierInfoId = []
            getSupplierSelector().then(res => res.data.forEach(item => state.filterData.supplierInfoId.push({name: item.shortName, value: item.supplierInfoId})))
            getTableList()
        })

        return {
            Plus,
            Search,
            ...toRefs(state),
            tableHeaderRef,
            sizeChange,
            currentChange,
            getTableList,
            directSend,
            wechatSend,
            removeQuotation,
            toPurchase,
            openDetail,
            radioChange,
            resetParams,
            dialogOpened,
            headerChange,
            submitHeader,
            createCallback,
            openForm
        }
    }
}
</script>

<style scoped lang="scss">
.page-container {
    .page-row {
        display: flex;
        flex-wrap: wrap;
        align-items: stretch;

        .tips-data {
            display: flex;
            align-items: center;
            height: 28px;
            margin-top: 20px;

            .tips {
                margin-right: 3px;
                font-size: 13px;
            }

            &:first-child {
                height: unset;
                margin-top: 0;
            }
        }

        .tips-cell {
            flex: auto;

            .tips-item {
                display: flex;
                align-items: center;
                padding-left: 10px;
                justify-content: space-between;
            }

            .tips-name {
                margin-right: 10px;
                flex: 1;
                overflow: hidden;
                text-align: center;
            }

            .item-data {
                text-align: center;
                height: 28px;
                margin-top: 20px;
                line-height: 28px;
                color: var(--el-menu-text-color);
                font-size: 13px;
            }

            .text-red {
                font-size: 24px;
                color: red;
            }

            .item-right {
                margin-right: 14px;
            }

            .red {
                color: var(--el-color-danger)
            }

            .green {
                color: var(--el-color-success);
            }
        }

        :deep(.el-table--border::before),
        :deep(.el-table--border::after),
        :deep(.el-table__inner-wrapper::before),
        :deep(.el-table__border-left-patch) {
            display: none;
        }

        :deep(.el-table--border .el-table__inner-wrapper tr:first-child th:first-child),
        :deep(.el-table--border .el-table__inner-wrapper tr:first-child td:first-child) {
            border-left: none !important;
        }

        :deep(.el-table--border .el-table__cell:last-child) {
            border-right: none;
        }

        :deep(.el-table__row) {
            &:last-child {
                .el-table__cell {
                    border-bottom: none;
                }
            }
        }
    }

    .table-box {
        background: #fff;
        margin-top: 10px;

        :deep(.el-table__header-wrapper .el-table__cell) {
            background: var(--el-color-primary-light-9);
            color: var(--next-bg-menuBar-light-1);
        }

        :deep(thead .cell) {
            display: flex;
            align-items: center;
            justify-content: center;
        }

        :deep(thead .el-icon) {
            margin-top: -2px;
            cursor: pointer;
        }

        .primary {
            cursor: pointer;
            color: var(--el-color-primary);
        }

        .short {
            display: block;
            text-overflow: ellipsis;
            overflow: hidden;
            white-space: nowrap;
        }

        .table-list {
            border: 1px solid var(--el-table-border-color);
            border-bottom: none;

            :deep(thead .cell) {
                display: flex;
                align-items: center;
                justify-content: center;
            }

            :deep(thead th:last-child .cell) {
                justify-content: center;
            }

            :deep(thead .el-icon) {
                margin-top: -2px;
                cursor: pointer;
            }

            .primary {
                cursor: pointer;
                color: var(--el-color-primary);
            }

            :deep(.el-button) {
                margin-left: 0;
                margin-right: 12px;
            }

            :deep(.el-table__body td.el-table__cell) {
                border-right: 1px solid var(--el-border-color-light);
                padding: 0;

                &:last-child {
                    border-right: none;
                }
            }

            .order-row-item {
                width: 100%;

                :deep(.el-col) {
                    border-right: 1px solid var(--el-border-color-light);
                    text-align: center;
                    display: flex;
                    align-items: center;
                    justify-content: center;

                    &:last-child {
                        border-right: none;
                    }

                    &:first-child,
                    &:nth-child(2) {
                        text-align: left;
                        justify-content: flex-start;
                        padding-left: 8px;
                    }
                }
            }

            .order-border-none {
                :deep(.el-col) {
                    border: none;
                }
            }
        }
    }
}
</style>
<style lang="scss">
.el-table__body .order-goods .cell {
    min-height: 70px;
    display: flex;
    align-items: stretch;
    padding: 0;
}
</style>
